<?php

class Auto_Modeler extends Model
{
	protected $data = array();

	public function __construct($id = NULL)
	{
		parent::__construct();

		if ($id != NULL)
		{
			// try and get a row with this ID
			$data = $this->db->getwhere($this->table_name, array('id' => $id))->result(FALSE);

			// try and assign the data
			if (count($data) == 1 AND $data = $data->current())
			{
				foreach ($data as $key => $value)
					$this->data[$key] = $value;
			}
		}
	}

	public function __destruct()
	{
		return TRUE;
	}

	public function __get($key)
	{
		if (isset($this->data[$key]))
			return $this->data[$key];
	}

	public function __set($key, $value)
	{
		if (empty($this->data[$key]) OR $this->data[$key] !== $value)
			$this->data[$key] = $value;
	}

	public static function factory($model = FALSE, $id = FALSE)
	{
		$model = empty($model) ? __CLASS__ : ucfirst($model).'_Model';
		return new $model($id);
	}

	public function set_fields($data)
	{
		foreach ($data as $key => $value)
			if (isset($this->data[$key]))
				$this->data[$key] = $value;
	}

	public function save()
	{
		if ($this->data['id']) // Do an update
			return count($this->db->update($this->table_name, $this->data, array('id' => $this->data['id'])));
		else // Do an insert
			return $this->db->insert($this->table_name, $this->data)->insert_id();
	}

	public function delete()
	{
		if ($this->data['id'])
		{
			$this->db->delete($this->table_name, array('id' => $this->data['id']));
			return $this->__destruct();
		}
	}

	public function fetch_all($current = 'all', $orderby = 'id', $direction = 'ASC')
	{
		if ($current != 'all' AND isset($this->data['current']))
			$this->db->where(array('current' => (bool) $current));

		return $this->db->orderby($orderby, $direction)->get($this->table_name)->result(TRUE, __CLASS__);
	}

	public function select_list($key, $display, $current = 'all')
	{
		$rows = array();

		foreach ($this->fetch_all($current) as $row)
			$rows[$row->$key] = $row->$display;

		return $rows;
	}
}